package cn.xerllent.wxtp.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.xerllent.common.service.impl.BaseServiceImpl;
import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.entity.WxTag;
import cn.xerllent.wxtp.service.WxTagService;
import cn.xerllent.wxtp.service.mapper.WxTagMapper;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceOnTpImpl;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpTagGetResult;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

@Service
//@AllArgsConstructor
//@CacheConfig(cacheNames = "user")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class WxTagServiceImpl extends BaseServiceImpl<WxTagMapper, WxTag>  implements WxTagService {

	/**
	 * 同步指定企业标签
	 * */
	@Override
	public void syncTags(WxCpTpService wxCpTpService, WxCorp wxCorp) {
		try {
			//第三方服务商service基础上构造授权企业service的代码api,另一种方式使用授权企业api
			WxCpService wxCpService = new WxCpServiceOnTpImpl(wxCpTpService);
			val configStorage = new WxCpDefaultConfigImpl();
			configStorage.setCorpId(wxCorp.getCorpId());
			configStorage.setCorpSecret(wxCorp.getPermanentCode());//从数据库中查找出permanentCode
			configStorage.setAgentId(wxCorp.getAgentId()); //生成jssdk sign时需要
			wxCpService.setWxCpConfigStorage(configStorage);
			
			//1. 获取标签列表
			List<WxCpTag> tags = wxCpService.getTagService().listAll();
			List<WxTag> wxTags = tags.stream().map(tag ->{
				WxTag itag= new WxTag().setCorpId(wxCorp.getCorpId())
						.setTagid(Integer.parseInt(tag.getId()))
						.setTagname(tag.getName());
				//2. 获取标签详情
				try {
					WxCpTagGetResult r = wxCpService.getTagService().get(tag.getId());
					itag.setUserlist(r.getUserlist().stream().map(u->u.getUserId()).collect(Collectors.toSet()));
					itag.setPartylist(r.getPartylist().stream().collect(Collectors.toSet()));
				} catch (WxErrorException e) {
					e.printStackTrace();
				}
				
				return itag;
			}).collect(Collectors.toList());
			
			//3先删除原来的标签
			remove(new LambdaQueryWrapper<WxTag>().eq(WxTag::getCorpId, wxCorp.getCorpId()));
			//4再保存现在的标签
			saveOrUpdateBatch(wxTags);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 清除对应Mapper的二级缓存，采用无害删除空数据模拟清空,因为二级缓存更新机制是本表数据更新即可清空<br>
	 * 提供本方法供联表更新查询的实时更新
	 * */
	@Override
	public void clearCache() {
		baseMapper.deleteById(0);
	}

}
